package com.sunday.aomicaichang.ui.my;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.ui.login.LoginActivity;
import com.sunday.member.SessionToken;
import com.sunday.member.entity.Member;
import com.sunday.member.entity.UploadImage;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/5/31.
 */

public class OwnerDataActivity extends BaseActivity {

    private final static int TYPE_NAME = 1;//修改昵称
    private final static int TYPE_LOGO = 2;//修改头像
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.tv_avator)
    TextView tvAvator;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.ly_avator)
    RelativeLayout lyAvator;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ly_name)
    RelativeLayout lyName;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.ly_phone)
    RelativeLayout lyPhone;
    @Bind(R.id.tv_login_password)
    TextView tvLoginPassword;
    @Bind(R.id.ly_login_password)
    RelativeLayout lyLoginPassword;
    @Bind(R.id.tv_pay_password)
    TextView tvPayPassword;
    @Bind(R.id.ly_pay_password)
    RelativeLayout lyPayPassword;
    @Bind(R.id.btn_exit)
    TextView btnExit;

    private String ava;
    private String name;
    private String phone;
    private Member member;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private static final int REQUEST_IMAGE = 2;
    private String localMain, netMain;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_owner_data);
        ButterKnife.bind(this);
        init();
    }
    private void init(){
        ava = BaseApp.getInstance().getMember().getImage();
        name = BaseApp.getInstance().getMember().getNickName();
        phone = BaseApp.getInstance().getMember().getMobile();
        if(ava!=null)
        Picasso.with(mContext)
                .load(ava)
                .error(R.mipmap.ic_avator)
                .resize(150,150).into(img);
        if(name!=null)
            tvName.setText(name);
        if(phone!=null)
            tvPhone.setText(phone);
        member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
        updateView();
    }
    @OnClick({R.id.ly_avator,R.id.ly_name,R.id.btn_exit,R.id.ly_login_password,R.id.ly_pay_password})
    void onClick(View v){
        switch (v.getId()){
            case R.id.ly_avator:
                intent = new Intent(mContext, MultiImageSelectorActivity.class);
                intent.putExtra(MultiImageSelectorActivity.
                        EXTRA_SHOW_CAMERA, true);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
            case R.id.ly_name:
                showNameDialog();
                break;
            case R.id.btn_exit:
                showLogoutDialog();
                break;
            case R.id.ly_login_password:
                Intent intent=new Intent(this,UpdateLoginPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.ly_pay_password:
                Intent intent1=new Intent(this,UpdatePaySetting1Activity.class);
                startActivity(intent1);
                break;

        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE:
                    mSelectPath.clear();
                    mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    if (mSelectPath != null) {
                        String logo = ImageUtils.getCompressImagePath(mSelectPath.get(0));
                        Picasso.with(mContext)
                                .load(new File(logo))
                                .placeholder(R.mipmap.ic_avator)
                                .error(R.mipmap.ic_avator)
                                .resize(130, 130)
                                .into(img);
                        uploadImg(UploadUtils.getRequestBody(logo));
                    }
                    break;
            }
        }
    }
    private void uploadImg(RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<UploadImage>> call= MemberClient.getApiAdapter().uploadSingle(requestBody);
        call.enqueue(new Callback<ResultDO<UploadImage>>() {
            @Override
            public void onResponse(Call<ResultDO<UploadImage>> call, Response<ResultDO<UploadImage>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext,"上传成功");
                    String imgs=response.body().getResult().getHalfPath();
                    saveInfo(imgs,TYPE_LOGO);

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<UploadImage>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }
    private void updateView() {
        if (!TextUtils.isEmpty(member.getImage())) {
            Picasso.with(mContext)
                    .load(member.getImage())
                    .error(R.mipmap.ic_avator)
                    .resize(130, 130)
                    .into(img);
        }
        tvName.setText(member.getNickName());
    }
    private void showNameDialog(){
        final AlertDialog myDialog = new AlertDialog.Builder(mContext).create();
        myDialog.setView(((Activity) mContext).getLayoutInflater().inflate(R.layout.dialog_edt, null));
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.dialog_edt);
        TextView tv_title = (TextView) myDialog.getWindow().findViewById(R.id.tv_order_num_title);
        tv_title.setText("请输入昵称");
        final EditText etNum = (EditText) myDialog.getWindow().findViewById(R.id.et_order_number);
        final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(etNum, InputMethodManager.SHOW_IMPLICIT);
        myDialog.getWindow()
                .findViewById(R.id.tv_order_num_cancel)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        imm.hideSoftInputFromWindow(etNum.getWindowToken(), 0);
                        myDialog.dismiss();
                    }
                });
        myDialog.getWindow()
                .findViewById(R.id.tv_order_num_confirm)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(etNum.getText().toString())) {
                            ToastUtils.showToast(OwnerDataActivity.this, "不能为空！");
                        } else {
                            tvName.setText(etNum.getText().toString());
                            saveInfo(tvName.getText().toString(),TYPE_NAME);
                            myDialog.dismiss();
                        }
                    }
                });
    }

    private void saveInfo(String str, final int type) {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{type == TYPE_NAME ? "nickName" : "image", "nonce"};
        String[] str2 = new String[]{str, nonce};
        showLoadingDialog(0);
        Call<ResultDO<Member>> call = null;
        if (type == TYPE_NAME) {
            call = MemberClient.getApiAdapter().updateUserInfo(str, null, null, null, null, null, null, nonce, SignUtil.getSign(str1, str2));
        } else {
            call = MemberClient.getApiAdapter().updateUserInfo(null, null, null, null, str, null, null, nonce, SignUtil.getSign(str1, str2));
        }
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    member = response.body().getResult();
                    ToastUtils.showToast(mContext, "修改成功");
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    BaseApp.getInstance().setMember(member);
                    SessionToken.accountId= String.valueOf(member.getId());
                    SessionToken.token = member.getToken();
                    if("nickName".equals(type))
                    tvName.setText(member.getNickName());
                    else
                    if (!TextUtils.isEmpty(member.getImage())) {
                        Picasso.with(mContext)
                                .load(member.getImage())
                                .error(R.mipmap.ic_avator)
                                .resize(130, 130)
                                .into(img);
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void showLogoutDialog(){
        final UIAlertView delDialog = new UIAlertView(mContext, "温馨提示", "退出登录？",
                "取消", "确定");
        delDialog.show();
        delDialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                                       @Override
                                       public void doLeft() {
                                           delDialog.dismiss();
                                       }

                                       @Override
                                       public void doRight() {
                                           SharePerferenceUtils.getIns(mContext).removeKey("oAuth");
                                           SharePerferenceUtils.getIns(mContext).removeKey(ConstValue.AREA);
                                           SharePerferenceUtils.getIns(mContext).removeKey(ConstValue.AREA_NAME);
                                           EventBus.getDefault().post(new ExitApp());
                                           intent = new Intent(mContext,LoginActivity.class);
                                           startActivity(intent);
                                           finish();
                                       }
                                   }
        );

    }
}
